全部学科
Python全栈
python
NodeJS全栈
nodejs
📅 2026-05-23 6 分钟 ✍️ juanwangdev

Rollup 钩子兼容性

Vite 插件兼容大部分 Rollup 钩子,但开发环境和构建环境行为有差异。

兼容的 Rollup 钩子

钩子开发环境构建环境
resolveId✓ 执行✓ 执行
load✓ 执行✓ 执行
transform✓ 执行✓ 执行
buildStart✗ 不执行✓ 执行
buildEnd✗ 不执行✓ 执行
generateBundle✗ 不执行✓ 执行

注意:构建阶段钩子在开发环境不执行。

开发环境特点

  • 只执行 resolveId、load、transform
  • 模块按需编译
  • 不生成最终产物

构建环境特点

  • 完整执行所有 Rollup 钩子
  • 生成最终构建产物
  • 执行 buildStart → buildEnd 流程

钩子执行示例

JavaScript
export default function myPlugin() {
  return {
    name: 'my-plugin',

    // 开发和构建都执行
    transform(code, id) {
      return transformCode(code)
    },

    // 只在构建时执行
    generateBundle(options, bundle) {
      // 处理构建产物
    }
  }
}

条件应用钩子

JavaScript
export default function myPlugin() {
  return {
    name: 'my-plugin',
    apply: 'build',  // 只在构建时生效
    generateBundle(options, bundle) {
      // 构建产物处理
    }
  }
}

Rollup 钩子详解

JavaScript
// buildStart - 构建开始
buildStart() {
  console.log('Build started')
}

// buildEnd - 构建结束
buildEnd() {
  console.log('Build ended')
}

// generateBundle - 生成产物
generateBundle(options, bundle) {
  for (const fileName in bundle) {
    const chunk = bundle[fileName]
    // 处理 chunk
  }
}

// writeBundle - 写入产物后
writeBundle(options, bundle) {
  // 产物写入完成
}

要点总结

  • Vite 兼容大部分 Rollup 钩子
  • 开发环境只执行模块处理钩子
  • 构建阶段钩子只在 build 时执行
  • apply 控制钩子生效环境
想在手机上练习这篇文章的配套题目?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码
← 上一篇 Vite 插件 Hook 体系
下一篇 → 编写 transform 钩子插件
扫码体验小程序
加载中
想在手机上刷题学习?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码